package com.zhuang.nettydemo.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class AppServer {

    private static final int PORT_NUM = 7788;

    public static void main(String[] args) {
        NioEventLoopGroup bossGroup = null;
        NioEventLoopGroup workerGroup = null;
        try {
            //1定义两个线程池组，一个处理连接，一个处理读写
            bossGroup = new NioEventLoopGroup(1);
            //会根据CPU核数，来计算线程池的大小
            workerGroup = new NioEventLoopGroup();

            //2服务启动助手
            ServerBootstrap bootstrap = new ServerBootstrap();
            //3助手绑定两个线程池组
            bootstrap.group(bossGroup, workerGroup)
                    //4指定类型的通道
                .channel(NioServerSocketChannel.class)
                //5处理初始化，编解码器，自定义hadder
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //6定义字符串编解码器
                        socketChannel.pipeline().addLast(new StringEncoder());
                        socketChannel.pipeline().addLast(new StringDecoder());
                        //7自定义处理器
                        socketChannel.pipeline().addLast(new MyServerHandler());
                    }
                });
            //7绑定端口号
            ChannelFuture channelFuture = bootstrap.bind(PORT_NUM).sync();
            System.out.println("服务启动成功！");
            //8以同步方式关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
